package com.zhs.gccs.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.util.Log;

import androidx.core.content.FileProvider;

import java.io.File;

/**
 * Package Utilities
 *
 * @author mcharima5@gmail.com, @redevelopment by aditnanda@nand.cloud
 * @since 2018
 */
public class PackageUtil {

    public static String getApplicationName(Context context) throws PackageManager.NameNotFoundException {
        return getPackageInfo(context).applicationInfo.loadLabel(context.getPackageManager()).toString();
    }

    public static String getPackageVersionName(Context context) throws PackageManager.NameNotFoundException {
        return getPackageInfo(context).versionName;
    }

    public static int getPackageVersionCode(Context context) throws PackageManager.NameNotFoundException {
        PackageInfo info = getPackageInfo(context);
        int packageVersionCode;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            packageVersionCode = (int) info.getLongVersionCode();
        } else {
            packageVersionCode = info.versionCode;
        }
        return packageVersionCode;
    }

    public static String getPackageName(Context context) throws PackageManager.NameNotFoundException {
        return getPackageInfo(context).packageName;
    }

    private static PackageInfo getPackageInfo(Context context) throws PackageManager.NameNotFoundException {
        return context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_META_DATA);
    }

    //1、申请两个权限：WRITE_EXTERNAL_STORAGE 和 REQUEST_INSTALL_PACKAGES ；2、配置FileProvider
    public static void installApk(Context context, File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", file);
            //【content://{$authority}/external/temp.apk】或【content://{$authority}/files/bqt/temp2.apk】
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//【file:///storage/emulated/0/temp.apk】
            uri = Uri.fromFile(file);
        }
        Log.i("bqt", "【Uri】" + uri);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

}
